package cn.est.serviceImpl;

import cn.est.dto.Page;
import cn.est.mapper.UsersMapper;
import cn.est.pojo.Users;
import cn.est.service.UsersService;
import cn.est.utils.EstSQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class UsersServiceImpl implements UsersService {

    @Autowired
    private UsersMapper usersMapper;

    public Users getUsersById(Long id) {
        return usersMapper.getUsersById(id);
    }

    public List<Users> getUsersListByMap(Map<String, Object> param) {
        return usersMapper.getUsersListByMap(param);
    }

    public Integer getUsersCountByMap(Map<String, Object> param) {
        return usersMapper.getUsersCountByMap(param);
    }

    public Integer qdtxAddUsers(Users users) {
        users.setCreatdTime(new Date());
        return usersMapper.insertUsers(users);
    }

    public Integer qdtxModifyUsers(Users users) {
        users.setUpdatedTime(new Date());
        return usersMapper.updateUsers(users);
    }

    public Integer qdtxDeleteUsersById(Long id) {
        return usersMapper.deleteUsersById(id);
    }

    public Integer qdtxBatchDeleteUsers(String ids) {
        Map<String, List<String>> param = new HashMap<String, List<String>>();
        String[] paramArrays = ids.split(",");
        List<String> idList = new ArrayList<String>();
        for (String temp : paramArrays) {
            idList.add(temp);
        }
        param.put("ids", idList);
        return usersMapper.batchDeleteUsers(param);
    }

    public Page<Users> queryUsersPageByMap(Map<String, Object> param, Integer pageNo, Integer pageSize) {
        Integer total = usersMapper.getUsersCountByMap(param);
        Page page = new Page(pageNo, pageSize, total);
        param.put("beginPos", page.getBeginPos());
        param.put("pageSize", page.getPageSize());
        List<Users> usersList = usersMapper.getUsersListByMap(param);
        page.setList(usersList);
        return page;
    }

     @Override
    public Users loginByPhone(String phone ) throws EstSQLException {
       //1.去数据库中查询是否存在此用户
         Users user= usersMapper.getUserByPhone(phone);

        //2.若没有存在则生成此用户放在数据库中
        if(user==null){
            //数据库不存在此用户，需要插入此用户到user表中
            Users u =new Users();
            u.setAccount(phone);
            u.setIsAuthentication(0);
            u.setCreatdTime(new Date());
            u.setIsDelete(0);
            int result=usersMapper.insertUsers(u);
            if(result<=0){
                throw  new EstSQLException("数据库异常插入数据失败");
            }
            return u;
        }
        //3.若存在则返回对象信息
        return user;
    }


}
